import matplotlib.pyplot as plt
import numpy as np
def approximate(d):
    unit = 0.25
    flag = True
    if d < 0:
        flag = False
        d = -d
    quotient = int(d / unit)
    remainder = d % unit

    if flag:
        if remainder < unit / 2:
            return unit * quotient
        else:
            return unit * (quotient + 1)
    else:
        if remainder < unit / 2:
            return -(unit * quotient)
        else:
            return -(unit * (quotient + 1))

def draw_pitch_pic(pitch_sum: list, begin=0, end=100):
    plt.bar(range(begin, end), pitch_sum[begin:end])
    plt.ylabel('times')
    plt.xlabel('pitch')
    plt.title("pure RMC")
    plt.show()

def pre_process(path):
    data = np.load(path, allow_pickle=True)

    data_T = data.T
    data_T[3] = np.round(data_T[3])
    data_T[5] = np.round(data_T[5])

    for pitch in range(0, len(data_T[4])):
        for sentence in range(0, len(data_T[4][pitch])):
            data_T[4][pitch][sentence] = approximate(data_T[4][pitch][sentence])

    data = data_T.T
    return data

def stat_pitch_sum(tuplt_list, init_list: list = None):
    this_pitch_list = tuplt_list
    pitch_list_sum = None

    if init_list == None:
        pitch_list_sum = list()
        for i in range(100):
            pitch_list_sum.append(0)
    # init

    else:
        pitch_list_sum = init_list

    for p in this_pitch_list:
        pitch_list_sum[int(p)] += 1

    return pitch_list_sum

raw_data =pre_process(
    r'D:\coding\melody-generator-gan\src\sangle_save\rmcgenera_2.npy')
r_list=[]
for times in range(100):
    r_list.extend(raw_data[times].T[3])

# raw_data = raw_data[0]
# r_list = [t[0] for t in raw_data]

sum_list = stat_pitch_sum(r_list)
# sum_list=stat_pitch_sum(r_list,init_list=sum_list)
draw_pitch_pic(sum_list, begin=0, end=100)
